package com.reactim.user.service.impl;

import com.reactim.user.entity.FriendGroup;
import com.reactim.user.entity.UserFriend;
import com.reactim.user.repository.FriendGroupRepository;
import com.reactim.user.repository.UserFriendRepository;
import com.reactim.user.service.FriendGroupService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 好友分组服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FriendGroupServiceImpl implements FriendGroupService {
    
    private final FriendGroupRepository friendGroupRepository;
    private final UserFriendRepository userFriendRepository;
    
    private static final String DEFAULT_GROUP_NAME = "我的好友";
    private static final int MAX_GROUPS_PER_USER = 20;
    
    @Override
    @Transactional
    public FriendGroup createGroup(Long userId, String name, String description) {
        // 验证分组名称
        if (name == null || name.trim().isEmpty()) {
            throw new IllegalArgumentException("分组名称不能为空");
        }
        
        // 检查分组数量限制
        long groupCount = friendGroupRepository.countByUserId(userId);
        if (groupCount >= MAX_GROUPS_PER_USER) {
            throw new IllegalArgumentException("分组数量已达上限");
        }
        
        // 检查分组名称是否重复
        if (friendGroupRepository.existsByUserIdAndName(userId, name.trim())) {
            throw new IllegalArgumentException("分组名称已存在");
        }
        
        // 获取下一个排序顺序
        Integer maxSortOrder = friendGroupRepository.findMaxSortOrderByUserId(userId);
        int nextSortOrder = (maxSortOrder != null ? maxSortOrder : 0) + 1;
        
        // 创建分组
        FriendGroup group = new FriendGroup();
        group.setUserId(userId);
        group.setName(name.trim());
        group.setDescription(description != null ? description.trim() : null);
        group.setSortOrder(nextSortOrder);
        group.setIsDefault(false);
        group.setIsSystem(false);
        
        FriendGroup savedGroup = friendGroupRepository.save(group);
        
        log.info("创建好友分组: userId={}, groupName={}, groupId={}", 
                userId, name, savedGroup.getId());
        
        return savedGroup;
    }
    
    @Override
    @Transactional
    public FriendGroup updateGroup(Long groupId, Long userId, String name, String description) {
        FriendGroup group = friendGroupRepository.findById(groupId)
                .orElseThrow(() -> new IllegalArgumentException("分组不存在"));
        
        // 验证权限
        if (!group.getUserId().equals(userId)) {
            throw new IllegalArgumentException("无权修改此分组");
        }
        
        // 系统分组不能修改名称
        if (group.getIsSystem() && !group.getName().equals(name)) {
            throw new IllegalArgumentException("系统分组不能修改名称");
        }
        
        // 验证分组名称
        if (name == null || name.trim().isEmpty()) {
            throw new IllegalArgumentException("分组名称不能为空");
        }
        
        // 检查分组名称是否重复（排除自己）
        Optional<FriendGroup> existingGroup = friendGroupRepository.findByUserIdAndName(userId, name.trim());
        if (existingGroup.isPresent() && !existingGroup.get().getId().equals(groupId)) {
            throw new IllegalArgumentException("分组名称已存在");
        }
        
        // 更新分组信息
        group.setName(name.trim());
        group.setDescription(description != null ? description.trim() : null);
        
        FriendGroup updatedGroup = friendGroupRepository.save(group);
        
        log.info("更新好友分组: groupId={}, newName={}", groupId, name);
        
        return updatedGroup;
    }
    
    @Override
    @Transactional
    public void deleteGroup(Long groupId, Long userId) {
        FriendGroup group = friendGroupRepository.findById(groupId)
                .orElseThrow(() -> new IllegalArgumentException("分组不存在"));
        
        // 验证权限
        if (!group.getUserId().equals(userId)) {
            throw new IllegalArgumentException("无权删除此分组");
        }
        
        // 默认分组和系统分组不能删除
        if (group.getIsDefault() || group.getIsSystem()) {
            throw new IllegalArgumentException("默认分组和系统分组不能删除");
        }
        
        // 将该分组中的好友移动到默认分组
        FriendGroup defaultGroup = getOrCreateDefaultGroup(userId);
        List<UserFriend> friendsInGroup = userFriendRepository.findByUserIdAndGroupId(userId, groupId);
        
        for (UserFriend friend : friendsInGroup) {
            friend.setGroupId(defaultGroup.getId());
            userFriendRepository.save(friend);
        }
        
        // 删除分组
        friendGroupRepository.delete(group);
        
        log.info("删除好友分组: groupId={}, 移动好友数量={}", groupId, friendsInGroup.size());
    }
    
    @Override
    public List<FriendGroup> getUserGroups(Long userId) {
        return friendGroupRepository.findByUserIdOrderBySortOrderAsc(userId);
    }
    
    @Override
    @Transactional
    public FriendGroup getOrCreateDefaultGroup(Long userId) {
        Optional<FriendGroup> defaultGroup = friendGroupRepository.findByUserIdAndIsDefaultTrue(userId);
        
        if (defaultGroup.isPresent()) {
            return defaultGroup.get();
        }
        
        // 创建默认分组
        FriendGroup group = new FriendGroup();
        group.setUserId(userId);
        group.setName(DEFAULT_GROUP_NAME);
        group.setDescription("默认好友分组");
        group.setSortOrder(0);
        group.setIsDefault(true);
        group.setIsSystem(true);
        
        FriendGroup savedGroup = friendGroupRepository.save(group);
        
        log.info("创建默认好友分组: userId={}, groupId={}", userId, savedGroup.getId());
        
        return savedGroup;
    }
    
    @Override
    @Transactional
    public void reorderGroups(Long userId, List<Long> groupIds) {
        if (groupIds == null || groupIds.isEmpty()) {
            return;
        }
        
        // 验证所有分组都属于该用户
        List<FriendGroup> groups = friendGroupRepository.findAllById(groupIds);
        for (FriendGroup group : groups) {
            if (!group.getUserId().equals(userId)) {
                throw new IllegalArgumentException("包含不属于当前用户的分组");
            }
        }
        
        // 更新排序顺序
        for (int i = 0; i < groupIds.size(); i++) {
            Long groupId = groupIds.get(i);
            FriendGroup group = groups.stream()
                    .filter(g -> g.getId().equals(groupId))
                    .findFirst()
                    .orElseThrow(() -> new IllegalArgumentException("分组不存在: " + groupId));
            
            group.setSortOrder(i + 1);
            friendGroupRepository.save(group);
        }
        
        log.info("调整好友分组排序: userId={}, groupCount={}", userId, groupIds.size());
    }
    
    @Override
    @Transactional
    public void moveFriendToGroup(Long userId, Long friendId, Long groupId) {
        // 验证好友关系
        UserFriend userFriend = userFriendRepository.findByUserIdAndFriendId(userId, friendId)
                .orElseThrow(() -> new IllegalArgumentException("好友关系不存在"));
        
        // 验证分组
        if (groupId != null) {
            FriendGroup group = friendGroupRepository.findById(groupId)
                    .orElseThrow(() -> new IllegalArgumentException("分组不存在"));
            
            if (!group.getUserId().equals(userId)) {
                throw new IllegalArgumentException("分组不属于当前用户");
            }
        }
        
        // 更新好友分组
        userFriend.setGroupId(groupId);
        userFriendRepository.save(userFriend);
        
        log.info("移动好友到分组: userId={}, friendId={}, groupId={}", userId, friendId, groupId);
    }
    
    @Override
    @Transactional
    public void moveFriendsToGroup(Long userId, List<Long> friendIds, Long groupId) {
        if (friendIds == null || friendIds.isEmpty()) {
            return;
        }
        
        // 验证分组
        if (groupId != null) {
            FriendGroup group = friendGroupRepository.findById(groupId)
                    .orElseThrow(() -> new IllegalArgumentException("分组不存在"));
            
            if (!group.getUserId().equals(userId)) {
                throw new IllegalArgumentException("分组不属于当前用户");
            }
        }
        
        // 批量更新好友分组
        List<UserFriend> userFriends = userFriendRepository.findByUserIdAndFriendIdIn(userId, friendIds);
        
        for (UserFriend userFriend : userFriends) {
            userFriend.setGroupId(groupId);
        }
        
        userFriendRepository.saveAll(userFriends);
        
        log.info("批量移动好友到分组: userId={}, friendCount={}, groupId={}", 
                userId, userFriends.size(), groupId);
    }
    
    @Override
    public long getFriendCountInGroup(Long userId, Long groupId) {
        if (groupId == null) {
            return userFriendRepository.countByUserIdAndGroupIdIsNull(userId);
        } else {
            return userFriendRepository.countByUserIdAndGroupId(userId, groupId);
        }
    }
}